<script setup>
import { ref, reactive, onMounted, watch, h } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useIuserInfoStore } from '@T2/store/users.ts';
import { statementApi as MainApi, statementById as MainById, optionApi } from '@T2/service/api.ts';
import { deepCopy, distributeAIntoB, buildTree } from '@T2/utils/utils.ts';
import { DeleteMain } from '@T2/utils/handleFnc.ts';
import dayjs from 'dayjs';
import MainDialog from './components/MainDialog.vue';

const iuserInfoStore = useIuserInfoStore();
const { getHandleRight } = iuserInfoStore;
const RIGHT = getHandleRight(['401', '402', '403']);

const emits = defineEmits(['option-change', 'statement-change']);

const optionRf = ref([]), statementRf = ref([]);
onMounted(async () => {
  const res = await Promise.all([getOptions(), getStatements()]);
  res[0].forEach(i => i._key = i.id + 'option');
  res[1].forEach(i => {
    i._key = i.id + 'statement';
    i.parent = i.option;
  });
  optionRf.value = res[0];
  statementRf.value = res[1];
  initTree();
});
const getOptions = () => {
  return new Promise((resolve, reject) => {
    optionApi({
      method: 'get',
      params: {
        type: '曲线分组',
      },
    }).then(res => {
      resolve(res.results || []);
    }).catch(() => {
      reject([]);
    });
  });
}
const getStatements = () => {
  return new Promise((resolve, reject) => {
    MainApi({
      method: 'get',
      params: {
        rtype: '分组',
      },
    }).then(res => {
      resolve(res.results || []);
    }).catch(() => {
      reject([]);
    });
  });
}

const Rt = reactive({
  tree: [],
  
  crtOption: null,
  crtStatement: null,
  
  currentID: null,
  filterText: '',
});
const treeRef = ref(null);
const initTree = () => {
  const arrA = deepCopy(statementRf.value);
  const arrB = deepCopy(optionRf.value);
  const { updatedB, unmatchedA } = distributeAIntoB(arrA, arrB, 'parent');
  const tree = buildTree(updatedB, 'parent');
  Rt.tree = tree.concat(unmatchedA);
  if (arrA.length) {
    setTimeout(() => {
      treeRef.value.setCurrentKey(arrA[0].id + 'statement');
    }, 100);
  }
}
watch(() => Rt.filterText, (nv) => {
  treeRef.value?.filter(nv);
});
const filterNode = (value, data, node) => {
  if (!value) {
    return true;
  }
  let obj = data, parentNode = node.parent, names = [];
  for(let level = node.level; level > 0; level--) {
    names = [...names, obj.name];
    obj = parentNode.data;
    parentNode = parentNode.parent;
  }
  return names.some(name => name.indexOf(value) !== -1);
}
const handleChange = (data, node) => {
  if (data.hasOwnProperty('option')) {
    Rt.crtOption = null;
    Rt.crtStatement = data.id;
    emits('statement-change', data, node);
  } else {
    Rt.crtOption = data.id;
    Rt.crtStatement = null;
    emits('option-change', data, node);
  }
}
const showColor = (data) => {
  if (data.disabled) {
    return 'rgba(18,30,52,0.4)';
  } else if ([Rt.crtStatement, Rt.crtOption].includes(data.id)) {
    return '#4D92F5';
  } else {
    return 'rgba(18,30,52,0.8)';
  }
}

/* 新增编辑弹窗 */
const MainDlgRt = reactive({
  show: false,
  type: '新增',
  dftData: null,
  row: null,
});
const handleMainDialog = (isAble = false, type, row = null) => {
  if (!isAble) {
    return;
  }
  MainDlgRt.type = type;
  MainDlgRt.show = true;
  MainDlgRt.dftData = type === '新增' ? { option_id: row?.id } : null;
  MainDlgRt.row = row;
}
const closeMainDialog = async (refresh = false) => {
  MainDlgRt.show = false;
  if (refresh) {
    refreshStatement();
  }
}
const refreshStatement = async () => {
  const res = await getStatements();
  res.forEach(i => {
    i._key = i.id + 'statement';
    i.parent = i.option;
  });
  statementRf.value = res;
  emits('option-change', null, null);
  treeRef.value.setCurrentKey('');
  initTree();
}
</script>

<template>
  <div class="tree flex-column">
    <el-tooltip placement="top" content="新增曲线" effect="dark" :show-after="500" v-if="!optionRf.length">
      <el-button type="primary" link style="margin-left: auto;" :disabled="!RIGHT['401']">
        <el-icon size="20" @click="handleMainDialog(RIGHT['401'], '新增')">
          <CirclePlus />
        </el-icon>
      </el-button>
    </el-tooltip>
    <el-input class="statement-filter" v-model="Rt.filterText" placeholder="输入名称进行筛选..." >
      <template #suffix>
        <el-icon><Search /></el-icon>
      </template>
    </el-input>
    <el-tree
      ref="treeRef"
      class="scroller-aside"
      node-key="_key"
      :highlight-current="true"
      :props="{label: 'name', disabled: 'disabled'}"
      :data="Rt.tree"
      :indent="15"
      :filter-node-method="filterNode"
      @current-change="handleChange"
    >
      <template #default="{ node, data }">
        <div
          class="el-tree-node__label flex--center"
          style="width: 100%;"
          :style="{color: showColor(data)}"
        >
          <p class="ellipsis" style="flex: 1;">{{ node.label }}</p>
          <div class="icons flex--center" :class="{ 'isActive': [Rt.crtStatement, Rt.crtOption].includes(data.id) }" style="margin-left: auto;">
            <template v-if="data.hasOwnProperty('option')">
              <el-button type="info" link :disabled="!RIGHT['402']">
                <el-icon size="18" @click="handleMainDialog(RIGHT['402'], '编辑', data)"><Edit /></el-icon>
              </el-button>
              <el-button type="danger" style="margin: 0;" link :disabled="!RIGHT['403']">
                <el-icon size="18" @click="DeleteMain(RIGHT['403'], MainById, data, '', refreshStatement)"><Delete /></el-icon>
              </el-button>
            </template>
            <template v-else>
              <el-tooltip placement="top" content="新增曲线" effect="dark" :show-after="500">
                <el-button type="primary" link :disabled="!RIGHT['401']">
                  <el-icon size="18" @click="handleMainDialog(RIGHT['401'], '新增', data)"><CirclePlus /></el-icon>
                </el-button>
              </el-tooltip>
            </template>
          </div>
        </div>
      </template>
    </el-tree>
  </div>
  
  <MainDialog
    :type="MainDlgRt.type"
    :row="MainDlgRt.row"
    :dftData="MainDlgRt.dftData"
    :options="optionRf"
    @closed="closeMainDialog"
    v-if="MainDlgRt.show"
  />
</template>

<style lang="scss" scoped>
.tree {
  width: 220px;
  height: 100%;
  position: relative;
  padding: 20px;
}
.icons {
  display: none;
  &.isActive {
    display: flex;
  }
}
</style>

<style scoped>
:deep(.statement-filter.el-input) {
  margin-bottom: 8px;
}
:deep(.statement-filter .el-input__wrapper) {
  box-shadow: none;
  border-bottom: 1px solid rgba(0,0,0,0.1);
  border-radius: 0;
}
:deep(.statement-filter .el-input__inner) {
  color: #121E34;
}

:deep(.el-tree) {
  flex: 1;
  overflow: overlay;
  overflow-x: hidden;
  border-radius: 3px;
  padding: 4px 0;
}
:deep(.is-current>.el-tree-node__content) {
  background-color: #F1F4FA !important;
}
:deep(.el-tree .el-icon) {
  margin-right: 4px;
}
:deep(.el-tree .el-tree-node__label) {
  font-size: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  position: relative;
}

:deep(.el-picker-panel__footer button.is-text) {
  /* 隐藏日期的【此刻】按钮 */
  display: none;
}

/* 多选变量 */
:deep(.el-checkbox) {
  margin: 0 20px;
  height: 25px;
}
:deep(.check-box .el-checkbox__label) {
  width: 200px;
  font-size: 12px;
  line-height: 20px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>